package com.example.demo.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Collections;

@Component("jedisLock")
public class JedisLock implements RedisLock {

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean lock(String lockValue, int seconds) {
        try(Jedis jedis = jedisPool.getResource()) {
            System.out.println("---------------lock------------------");
            boolean result = "OK".equals(jedis.set(lockValue, lockValue, "NX", "EX", seconds));
            return result;
        }
    }

    @Override
    public boolean tryLock(String lockValue, int seconds) {
        return false;
    }

    @Override
    public boolean release(String lock) {
        // 从redis从查找key=value的元素，找到就调用redis删除，返回删除结果，否则返回0
        String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end";
        try(Jedis jedis = jedisPool.getResource()) {
            // eval(lua脚本,key数组,参数数组)
            final Object eval = jedis.eval(luaScript, Collections.singletonList(lock), Collections.singletonList(lock));
            return eval.equals(1L);
        }
    }
}
